<?php
namespace app\mini\model;

use app\admin\model\PersonModel;
use app\crm\model\Customer;
use app\mini\controller\QyWechatController;
use think\facade\Db;
use app\common\traits\ActionRecordTrait;
use think\Model;
use app\admin\controller\ApiCommon;
//use app\mini\controller\QyWechatController;

use app\crm\model\CustomerLossModel;
use app\crm\model\OrderStatistics;
use app\admin\model\ShopOrderModel;
use app\admin\model\CustomerModel;
use app\admin\model\ShopModel;
use app\shop\model\Refund as OrderModel;
use app\mini\model\MiniStisticsModel;
use app\mini\model\CustomerPointGoodsBuy;



class SysModelMiniCustomer extends Model

{
    /**

     * @var string

     */

    protected $name = 'admin_sys';


    protected $defaultSoftDelete = 0;


    protected $autoWriteTimestamp = true;


    /**

     * 新增客户服务评价

     * @return array

     * @author ran

     * @date 2021-09-23 13:53

     * mailbox 466180170@qq.com

     */
    public function addEvaluation($request): array
    {

        $create_time = time();

        $customer_id = $request['customerId'];
        $serviceLog_id = $request['rateId'];
        $scoreValue = $request['rateValue'];
        $rate_text = $request['rateText'];
        $score_one = $request['score_one']??null;
        $score_two = $request['score_two']??null;
        $score_three = $request['score_three']??null;
        $score_four = $request['score_four']??null;


        if($scoreValue == '1'){
            $score_amount = '0';
        }else if($scoreValue == '2'){
            $score_amount = '40';
        }else if($scoreValue == '3'){
            $score_amount = '60';
        }else if($scoreValue == '4'){
            $score_amount = '80';
        }else if($scoreValue == '5'){
            $score_amount = '100';
        }

        $shop_id = Db::name('customer')->where('id',$customer_id)->value('shop_id');

        // $data = [
        //     'servicelog_id' => $serviceLog_id,
        //     'customer_id'   => $customer_id,
        //     'shop_id'       => $shop_id,
        //     'score_amount'  => $score_amount,
        //     'rate_text'     => $rate_text,
        //     'score_one'     =>$score_one,
        //     'score_two'     =>$score_two,
        //     'score_three'   =>$score_three,
        //     'score_four'    =>$score_four,
        //     'create_time'   => $create_time,
        // ];

        // echo "<pre>";
        // print_r($data);
        // echo "</pre>";
        // exit;
        try {

            $is_evalution = Db::name('service_log')->where('id', $serviceLog_id)->column('is_evaluation,book_id');

            // echo "<pre>";
            // print_r($is_evalution);
            // echo "</pre>";
            // exit;

            if($is_evalution[0]['is_evaluation'] == '0'){

                $where = [];

                if($is_evalution[0]['book_id']){
                    
                    array_push($where,['book_id','=',$is_evalution[0]['book_id']]);

                    $serviceLogs = Db::name('service_log')->where($where)->select()->toArray();
    
                    // echo "<pre>";
                    // print_r($serviceLogs);
                    // echo "</pre>";
                    // exit;
    
                    foreach ($serviceLogs as $key => $value) {
    
                        $data = [];
    
                        $data = [
                            'servicelog_id' => $value['id'],
                            'customer_id'   => $customer_id,
                            'shop_id'       => $shop_id,
                            'score_amount'  => $score_amount,
                            'rate_text'     => $rate_text,
                            'score_one'     =>$score_one,
                            'score_two'     =>$score_two,
                            'score_three'   =>$score_three,
                            'score_four'    =>$score_four,
                            'create_time'   => $create_time,
                        ];
    
                        $rate_id = Db::name('service_log_evaluation')->insertGetId($data);
    
                        if($rate_id){
    
                            $updateArr = [
                                'is_evaluation' => 1,
                            ];
    
                            $bool = Db::name('service_log')->where(['id' => $value['id']])->update($updateArr);
    
                        }
    
                    }
                }

                

                $where = [];
                $date = strtotime((date("Y-m",time())));
//                array_push($where,['origin_id','=',8]);
                array_push($where,['customer_id','=',$customer_id]);
                array_push($where,['create_time','>=',$date]);
                $evaluation = Db::name('service_log_evaluation')->where($where)->count();
                $where = [];
                array_push($where,['id','=',$serviceLog_id]);
                $serviceTime = Db::name('service_log')->where($where)->value('create_time');
                if(empty($serviceTime))
                {
                    $serviceTime=0;
                }
                if($serviceTime>=1694707200){
                    if(empty($evaluation))
                    {
                        CustomerPointModel::pointChange($customer_id,8);

                    }else{
                        CustomerPointModel::pointChange($customer_id,7);

                    }
                }

                return ['error' => '评价成功'];

            }else{

                return ['error' => '该服务您已经评价过了，请勿重复提交'];

            }



        } catch (\Throwable $e) {

            return ['error' => $e->getMessage()];

        }

    }

    public function addEvaluationCeShi($request): array
    {

        $create_time = time();

        $customer_id = $request['customerId'];
        $serviceLog_id = $request['rateId'];
        $scoreValue = $request['rateValue'];
        $rate_text = $request['rateText'];
        $score_one = $request['score_one']??null;
        $score_two = $request['score_two']??null;
        $score_three = $request['score_three']??null;
        $score_four = $request['score_four']??null;


        if($scoreValue == '1'){
            $score_amount = '0';
        }else if($scoreValue == '2'){
            $score_amount = '40';
        }else if($scoreValue == '3'){
            $score_amount = '60';
        }else if($scoreValue == '4'){
            $score_amount = '80';
        }else if($scoreValue == '5'){
            $score_amount = '100';
        }

        $shop_id = Db::name('customer')->where('id',$customer_id)->value('shop_id');

        // $data = [
        //     'servicelog_id' => $serviceLog_id,
        //     'customer_id'   => $customer_id,
        //     'shop_id'       => $shop_id,
        //     'score_amount'  => $score_amount,
        //     'rate_text'     => $rate_text,
        //     'score_one'     =>$score_one,
        //     'score_two'     =>$score_two,
        //     'score_three'   =>$score_three,
        //     'score_four'    =>$score_four,
        //     'create_time'   => $create_time,
        // ];

        // echo "<pre>";
        // print_r($data);
        // echo "</pre>";
        // exit;
        // try {

            $is_evalution = Db::name('service_log')->where('id', $serviceLog_id)->column('is_evaluation,book_id');

            // echo "<pre>";
            // print_r($is_evalution);
            // echo "</pre>";
            // exit;

            if($is_evalution[0]['is_evaluation'] == '0'){


                $where = [];

                array_push($where,['book_id','=',$is_evalution[0]['book_id']]);

                $serviceLogs = Db::name('service_log')->where($where)->select()->toArray();

                // echo "<pre>";
                // print_r($serviceLogs);
                // echo "</pre>";
                // exit;

                foreach ($serviceLogs as $key => $value) {

                    $data = [];

                    $data = [
                        'servicelog_id' => $value['id'],
                        'customer_id'   => $customer_id,
                        'shop_id'       => $shop_id,
                        'score_amount'  => $score_amount,
                        'rate_text'     => $rate_text,
                        'score_one'     =>$score_one,
                        'score_two'     =>$score_two,
                        'score_three'   =>$score_three,
                        'score_four'    =>$score_four,
                        'create_time'   => $create_time,
                    ];

                    $rate_id = Db::name('service_log_evaluation')->insertGetId($data);

                    if($rate_id){

                        $updateArr = [
                            'is_evaluation' => 1,
                        ];

                        $bool = Db::name('service_log')->where(['id' => $value['id']])->update($updateArr);

                    }

                }


                if(!empty($request['is_first']))
                {
                    CustomerPointModel::pointChange($customer_id,8);

                }else{
                    CustomerPointModel::pointChange($customer_id,7);

                }

                return ['error' => '评价成功'];

            }else{

                return ['error' => '该服务您已经评价过了，请勿重复提交'];

            }



        // } catch (\Throwable $e) {

        //     return ['error' => $e->getMessage()];

        // }

    }


    public function getScheduleList($request): array
    {

        $time = time();
        $year = date('Y',$time);
        $month = date('m',$time);
        $t = date('t',$time)+7;

        $initialTime = strtotime($year.'-'.$month.'-'.'01');

        $staffIds = $request['staffIds'];

        // echo "<pre>";
        // print_r($staffIds);
        // echo "</pre>";
        // exit;

        $list = [];
        $timeS=[];
        $days = [];
        $md = [];
        $staffName = Db::name('shop_person')->where('id','in',$staffIds)->column('name,id');
        for($i=0;$i<$t;$i++){
            $timeS = $initialTime+86400*$i;
            array_push($days,date('Ymd',$timeS));
            array_push($md,date('m-d',$timeS));

        }

        $where = [];

        array_push($where,['shop_person_id','in',$staffIds]);

        array_push($where,['time','in',$days]);

        $scheduleRes = Db::name('shop_person_schedule')->where($where)->column('is_work,work_type,shop_person_id,time');
        $result = [];
        foreach($scheduleRes as $key => $value)
        {
            $result[$value['shop_person_id']][$value['time']]=$value;
        }

        // $schedule = [];
        foreach($staffName as $value)
        {
            $temp = [];
            $temp['id'] = $value['id'];
            $temp['name'] = $value['name'];
            foreach($days as $k => $v)
            {
                if(!empty($result[$value['id']][$v])&&$result[$value['id']][$v]['is_work'] == 1){

                    switch($result[$value['id']][$v]['work_type']){
                        case 0:{
                            $temp[$md[$k]] = "1";
                            break;
                        }
                        case 1:{
                            $temp[$md[$k]] = "2";
                            break;
                        }
                        case 2:{
                            $temp[$md[$k]] = "3";
                            break;
                        }
                    }

                }else{

                    $temp[$md[$k]] = '0';

                }

            }
            $temp['year'] = $year;

            array_push($list,$temp);
        }


        /*foreach ($staffIds as $key => $value) {

            $one = [];

            $staffName = Db::name('shop_person')->where('id',$value)->value('name');

            $one['id'] = $value;

            $one['name'] = $staffName;

            $one['year'] = $year;

            for($i=0;$i<$t;$i++){

                $timeS = $initialTime+86400*$i;

                $days = date('Ymd',$timeS);

                $k = date('m-d',$timeS);

                // $k = $month.'-'.$i;

                // if($i<10){

                //     $i = '0'.$i;

                // }

                // $days = '';

                // $days = $year.$month.$i;

                $where = [];

                array_push($where,['shop_person_id','=',$value]);

                array_push($where,['time','=',$days]);

                $scheduleRes = Db::name('shop_person_schedule')->where($where)->value('is_work');

                $workType = Db::name('shop_person_schedule')->where($where)->value('work_type');


                if($scheduleRes){

                    switch($workType){
                        case 0:{
                            $one[$k] = "1";
                            break;
                        }
                        case 1:{
                            $one[$k] = "2";
                            break;
                        }
                        case 2:{
                            $one[$k] = "3";
                            break;
                        }
                    }

                }else{

                    $one[$k] = '0';

                }

            }

            array_push($list,$one);

        }*/

        return [
            'msg' => '模型',

            'data' => $list,
        ];
    }

    public function setSchedule($request)
    {

        $data = array();
        foreach($request['data'] as $val)
        {

            $year = $request['year'];

            $date = explode('-',$val['date']);

            $staffId = $request['id'];

            $month = $date[0];

            $day = $date[1];

            $shop_id = $request['shop_id'];

            $isWork = $val['is_work'];

            $workType = $val['work_type'];

            $timeStr = strtotime($year.'-'.$month.'-'.$day);

            $time = date("Ymd",$timeStr);

            // $dayOfWeek = date('w',$timeStr);


            $workTime = "";

            if($workType != 0)
            {
                $where=array();

                array_push($where,['shop_id','=',$shop_id]);

                if($workType == 1)
                {
                    $workTime = DB::name('shop')->where($where)->value('am_work');
                }else{
                    $workTime = DB::name('shop')->where($where)->value('pm_work');
                }
                if(empty($workTime))
                {
                    $this->error = "未设置上午/下午班时间";
                    return false;
                }
            }


            $yyTime = "00000000000000000000000";

            if($workTime)
            {
                $workTime = explode('-',$workTime);

                $timeSub = explode(':',$workTime[0]);

                $start_num = (intval($timeSub[0])+intval($timeSub[1])/60 - 9)*2;

                $timeSub = explode(':',$workTime[1]);

                $end_num = (intval($timeSub[0])+intval($timeSub[1])/60 - 9)*2;

                $yyTime = str_split($yyTime,1);

                for($i = 0 ;$i<$start_num;$i++)
                {
                    $yyTime[$i]='-';
                }
                for($i = 22;$i>$end_num;$i--)
                {
                    $yyTime[$i]='-';
                }

                $yyTime = implode('',$yyTime);
            }

            $where = [];

            array_push($where,['shop_person_id','=',$staffId]);

            array_push($where,['time','=',$time]);

            $schedule = Db::name('shop_person_schedule')->where($where)->select()->toArray();
            if($schedule){
                if(strpos($schedule[0]['yy_time'],'1') !== false){
                        // return ['msg' => '编辑失败', 'data' => [],'code'=>300];
                        $this->error = "已被预约";
                        return false;
                    }else{
                        $updateArr = [
                            "is_work" => $isWork,
                            "yy_time" => $yyTime,
                            "work_type" => $workType
                        ];
                        $where = [];

                        array_push($where,['shop_person_id','=',$staffId]);

                        array_push($where,['time','=',$time]);

                        $res = Db::name('shop_person_schedule')->where($where)->update($updateArr);
                        if($res){
                            array_push($data,['id'=>$staffId,'msg'=>"编辑完成",'date'=>$time]);
                        }else{
                            array_push($data,['id'=>$staffId,'msg'=>"编辑失败",'date'=>$time]);
                        }
                    }
                }else{

                    $insertArr=[
                        "time"=>$time,
                        "shop_id"=>$shop_id,
                        "shop_person_id"=>$staffId,
                        "is_work"=>$isWork,
                        "yy_time"=>$yyTime,
                        "work_type"=>$workType,
                        "create_time"=>time()
                    ];

                    $res = Db::name('shop_person_schedule')->save($insertArr);

                    if($res){
                        return ['msg' => '编辑成功', 'data' => [],'code'=>200];
                        // $this->error = "保存失败";
                        // return false;
                        // return ['id'=>$staffId,'msg'=>"添加失败",'date'=>$time];
                        // array_push($data,['id'=>$staffId,'msg'=>"添加完成",'date'=>$time]);
                    }else{
                        array_push($data,['id'=>$staffId,'msg'=>"添加失败",'date'=>$time]);
                    }
                }

            }
            return ['msg' => '编辑成功', 'data' => [],'code'=>200];
    }

    // 获取客户所属门店的详情
    public function getShopInfo($request): array
    {
        $customer_id = $request['customer_id'];

        $where = [];

        array_push($where,['id','=',$customer_id]);

        $shopId = Db::name('customer')->where($where)->value('shop_id');

        $shop_where = [];

        array_push($shop_where,['shop_id','=',$shopId]);

        $shopInfo = Db::name('shop')->where($shop_where)->select()->toArray();

        // echo "<pre>";
        // print_r($shopInfo);
        // echo "</pre>";

        $shop_name  = $shopInfo[0]['shop_name'];

        $shop_tel   = $shopInfo[0]['shop_phone'];

        $start_time = $shopInfo[0]['start_time'];

        $end_time   = $shopInfo[0]['end_time'];

        $address    = $shopInfo[0]['address'];

        $data = [

            'shop_id' => $shopId,

            'shop_name' => $shopInfo[0]['shop_name'],

            'shop_tel' => $shopInfo[0]['shop_phone'],

            'start_time' => $shopInfo[0]['start_time'],

            'end_time' => $shopInfo[0]['end_time'],

            'address' => $shopInfo[0]['address'],

        ];

        // exit;

        return $data;
    }

    // 获取可预约日期
    public function bookDate(): array
    {
        $today = date("Y-m-d",time());

        $todayTimeStr = strtotime($today);


        $dateList = [];

        for($i=0;$i<=7;$i++){

            $timeStr = $todayTimeStr+86400*$i;

            $one = [];

            $one['year'] = date('Y',$timeStr);

            $one['month'] = date('m',$timeStr);

            $one['day'] = date('d',$timeStr);

            $one['date'] = $one['month'].'-'.$one['day'];

            array_push($dateList,$one);

        }

        return $dateList;

    }

    public function bookTime($request): array
    {

        $shop_id = $request['shop_id'];

        $start_time = $request['start_time'];

        $end_time = $request['end_time'];

        $year = $request['year'];

        $date = $request['date'];

        $timeStr = strtotime($year.'-'.$date); // 查询当天时间戳

        $time = date('Ymd',$timeStr); // 查询当天日期

        $where = [];

        array_push($where,['shop_id','=',$shop_id]);

        array_push($where,['time','=',$time]);

        array_push($where,['is_work','=','1']);

        $staffWorkList = Db::name('shop_person_schedule')->where($where)->select()->toArray();

        // echo "<pre>";
        // print_r($staffWorkList);
        // echo "</pre>";

        $list = [];

        if($staffWorkList){
            // 有排班

            $yy = str_split($staffWorkList[0]['yy_time']);

            // echo "<pre>";
            // print_r($yy);
            // echo "</pre>";

            // $startWorkTime = $year.'-'.$date.' '.$start_time;

            // echo $startWorkTime;
            // exit;

            $startWorkTimeStr = strtotime($year.'-'.$date.' '.$start_time); // 查询当天开始工作时间

            $endWorkTimeStr = strtotime($year.'-'.$date.' '.$end_time); // 查询当天开始工作时间

            foreach ($yy as $key => $value) {

                $one = [];

                // $showTimeStr = $startWorkTimeStr+$key*3600; // 时间间隔为1小时
                $showTimeStr = $startWorkTimeStr+$key*1800; // 时间间隔为半小时

                $showTime = date('H:i',$showTimeStr);

                if($showTimeStr>time() && $showTimeStr<$endWorkTimeStr){

                    $is_yy = 1;

                }else{

                    $is_yy = 0;

                }

                $one['showTime'] = $showTime;

                $one['is_yy'] = $is_yy;

                $one['id'] = 'time'.$key.$year;

                array_push($list,$one);

            }




        }else{
            // 无排班
        }

        // foreach ($staffWorkList as $key => $value) {


        // }

        // exit;

        return [
            'data' => $list,
        ];
    }

    public function bookTime2($request): array
    {

        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";
        // exit;

        $staff_id = $request['staff_id'] ?? '';

        $shop_id = $request['shop_id'];

        $start_time = $request['start_time'];

        $end_time = $request['end_time'];

        $year = $request['year'];

        $date = $request['date'];

        $timeStr = strtotime($year.'-'.$date); // 查询当天时间戳

        $time = date('Ymd',$timeStr); // 查询当天日期

        $where = [];

        array_push($where,['shop_id','=',$shop_id]);

        array_push($where,['time','=',$time]);

        array_push($where,['is_work','=','1']);

        array_push($where,['shop_person_id','=',$staff_id]);

        $staffWorkList = Db::name('shop_person_schedule')->where($where)->select()->toArray();

        // echo "<pre>";
        // print_r($staffWorkList);
        // echo "</pre>";
        // exit;

        $list = [];

        if($staffWorkList){
            // 有排班

            $yy = str_split($staffWorkList[0]['yy_time']);

            $startWorkTimeStr = strtotime($year.'-'.$date.' '.$start_time); // 查询当天开始工作时间

            $endWorkTimeStr = strtotime($year.'-'.$date.' '.$end_time); // 查询当天开始工作时间

            foreach ($yy as $key => $value) {

                $one = [];

                // $showTimeStr = $startWorkTimeStr+$key*3600; // 时间间隔为1小时
                $showTimeStr = $startWorkTimeStr+$key*1800; // 时间间隔为半小时

                $showTime = date('H:i',$showTimeStr);

                if($showTimeStr>time() && $showTimeStr<$endWorkTimeStr && $value == '0'){

                    $is_yy = 1; // 可预约

                }else{

                    $is_yy = 0; // 不可预约

                }


                $one['showTime'] = $showTime;

                $one['is_yy'] = $is_yy;

                $one['id'] = $key;

                $one['is_checked'] = '';

                $one['is_fill'] = $value;

                array_push($list,$one);

            }




        }else{
            // 无排班
        }



        return [
            'data' => $list ?? [],
        ];
    }

    public function getYYStaff($request): array
    {

        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";

        $year = $request['year'];

        $date = $request['date'];

        $shop_id = $request['shop_id'];

        $showYYTime = $request['showYYTime'];

        $timeStr = strtotime($year.'-'.$date); // 查询当天时间戳

        $time = date("Ymd",$timeStr);

        // 门店上下班时间
        $start_time = Db::name('shop')->where('shop_id',$shop_id)->value('start_time');

        // echo "<pre>";
        // print_r($shop_info);
        // echo "</pre>";

        $startWorkTimeStr = strtotime($year.'-'.$date.' '.$start_time); // 查询当天开始工作时间

        $yy_this_time = strtotime($year.'-'.$date.' '.$showYYTime); // 查询当天开始工作时间

        $subTime = bcsub($yy_this_time,$startWorkTimeStr,0);

        $numKey = floor($subTime/1800); // 预约时间在‘yy_time’中的位数（key值，第一个为0，第二个为1，。。。）

        $where = [];

        array_push($where,['position_id','in',[2,4,7,8,9,10]]);

        array_push($where,['shop_id','=',$shop_id]);

        array_push($where,['status','=','1']); // 在职

        $staffList = Db::name('shop_person')->where($where)->column('id,name,station_name,position_name,shop_id');

        // echo "<pre>";
        // print_r($staffList);
        // echo "</pre>";
        // exit;

        $where = [];

        array_push($where,['time','=',$time]);

        array_push($where,['shop_id','=',$shop_id]);

        $paiBanList = Db::name('shop_person_schedule')->where($where)->column('yy_time,shop_person_id,is_work','shop_person_id');

        // echo "<pre>";
        // print_r($paiBanList);
        // echo "</pre>";
        // exit;


        $shop_person_ids = array_values(array_unique(array_column($paiBanList,'shop_person_id')));

        $where = [];

        array_push($where,['shop_person_id','in',$shop_person_ids]);

        $shop_person_names = Db::name('admin_user')->where($where)->column('img','shop_person_id');

        // echo "<pre>";
        // print_r($shop_person_names);
        // echo "</pre>";
        // exit;


        $list = [];

        foreach ($staffList as $key => $value) {

            $one = [];

            $one['id'] = $value['id'] ?? '';

            $one['name'] = $value['name'] ?? '';

            $one['station_name'] = $value['station_name'] ?? '';

            $one['position_name'] = $value['position_name'] ?? '';

            $one['img'] = $shop_person_names[$value['id']] ?? '';

            $isPaiBan = $paiBanList[$value['id']]['yy_time'] ?? '';

            if($isPaiBan){

                if($paiBanList[$value['id']]['is_work'] == '1'){ // $isPaiBan ||

                    $yy_time_list = str_split($isPaiBan);

                    if($yy_time_list[$numKey]<1){ // 单位时间内预约的人数

                        $one['is_yy'] = 1;

                    }else if($yy_time_list[$numKey] == 1){ // 单位时间内预约的人数

                        $one['is_yy'] = 2;

                    }

                }else{

                    $one['is_yy'] = 0;

                }

            }else{

                $one['is_yy'] = 0;

            }


            array_push($list,$one);

        }

        return [

            'msg' => 'model',

            'data' => $list,

        ];
    }

    // 新增预约
    public function addYYData($request):array
    {
        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";

        $customer_id = $request['customer_id'];

        if($customer_id < 1){

            return ['msg' => '获取登陆人信息失败，请重新授权登录！'];
            exit;

        }

        $shop_person_id = $request['shop_person_id'];

        $year = $request['yy_year'];

        $date = $request['yy_date'];

        $time = $request['yy_time'];

        $shop_id = $request['shop_id'];

        $addRes = $this->addNewData($customer_id,$shop_person_id,$year,$date,$time,$shop_id);

        if($addRes['msg'] == '预约成功！'){

            // echo "修改员工排班数据";
            $bookRes = $this->updateStaffData($shop_person_id,$year,$date,$time,$shop_id,'add');

            return ['msg' => '预约成功！'];

        }else{

            return ['msg' => $addRes['msg']];

        }



    }

    // 新增预约
    public function addYYData2($request,$app):array
    {

        

        if($request['customer_id'] == '141222'){
            echo "<pre>";
            print_r($request);
            echo "</pre>";
            exit;
        }

        // 事务
        try {
            $customer_id = $request['customer_id'];

            if($customer_id < 1){

                return ['error' => '获取登陆人信息失败，请重新授权登录！'];
                exit;

            }

            $shop_person_id = $request['shop_person_id'];

            $year = $request['yy_year'];

            $date = $request['yy_date'];

            $time = $request['yy_time'];

            $shop_id = $request['shop_id'];


            $no_book_time = "";

            $time_rollback = [];

            foreach ($time as $key => $value) {

                $bookRes = $this->updateStaffData($shop_person_id,$year,$date,$value,$shop_id,'add');

                if(is_bool($bookRes) === false){
                    if($no_book_time == ""){
                        $no_book_time = $bookRes;
                    }else{
                        $no_book_time = $no_book_time.",".$bookRes;
                    }
                }else{

                    array_push($time_rollback,$value);

                }

            }

            // echo "<pre>";
            // print_r($time_rollback);
            // echo "</pre>";
            // exit;

            if($no_book_time){

                foreach ($time_rollback as $key => $value) {

                    $bookRes = $this->updateStaffData($shop_person_id,$year,$date,$value,$shop_id,'sub');

                }

                return ['error' => $no_book_time.'已约满！'];
                exit;

            }

            $addRes = $this->addNewData2($customer_id,$shop_person_id,$year,$date,$time,$shop_id);



            if($addRes['msg'] != '预约成功！'){

                // var_dump($addRes);
                return ['error' => $addRes['msg'], 'data' => []];
                exit;

            }

            CustomerPointModel::pointChange($customer_id,6);
            $customer = Customer::find($customer_id);
            $person = PersonModel::find($shop_person_id);
            $qyWechat = new QyWechatController($app);
            $stopTime = $year.'-'.$date.' '.$time[count($time)-1];
            $stopTime = date('H:i',strtotime($stopTime)+30*60);
            $qyWechat->index('setReservationAction',[
                'mobile'=>$person->phone,
                'start'=>$year.'-'.$date.' '.$time[0],
                'end'=>$stopTime,
                'customer_name'=>$customer->customer_name
            ]);

            Db::commit();


            return ['error' => '预约成功', 'data' => []];

        } catch (\Throwable $e) {
            Db::rollback();

            // $this->error = $e->getMessage();

            return ['error' => $e->getMessage()];
        }



    }

    // 预约数据新增数据库
    public function addNewData2($customer_id,$shop_person_id,$year,$date,$time,$shop_id)
    {

        if($time){

            $yyTime = strtotime($year.'-'.$date.' '.$time[0]); // 顾客预约时间戳

        }else{

            return $res = [

                'msg' => 'error!',

            ];

            exit;
        }

        $yy_time_str = implode(',',$time);

        // echo $yy_time_str;
        // exit;

        $where = [];

        array_push($where,['yy_time','=',$yyTime]);

        array_push($where,['customer_id','=',$customer_id]);

        array_push($where,['status','=',0]);


        $bookInfo = Db::name('books')->where($where)->select()->toArray();

        if($bookInfo){ // 请勿重复预约

            $msg = '您已预约当前时间，请勿重复预约！';

        }else{

            $data = [

                'customer_id' => $customer_id,

                'shop_person_id' => $shop_person_id,

                'shop_id' => $shop_id,

                'yy_time' => $yyTime,

                'yy_time_str' => $yy_time_str,

                'create_time' => time(),

                'status' => 0, // 0代表正常，1代表取消，

            ];

            $bookId = Db::name('books')->insertGetId($data); // 新增xy_books表数据


            if($bookId){

                $msg = '预约成功！';

            }else{

                $msg = '预约失败，请重新提交！';

            }

        }

        return $res = [

            'msg' => $msg,

        ];

        // exit;
    }

    // 预约数据新增数据库
    public function addNewData($customer_id,$shop_person_id,$year,$date,$time,$shop_id)
    {

        $yyTime = strtotime($year.'-'.$date.' '.$time); // 顾客预约时间戳

        $where = [];

        array_push($where,['yy_time','=',$yyTime]);

        array_push($where,['customer_id','=',$customer_id]);

        array_push($where,['status','=',0]);


        $bookInfo = Db::name('books')->where($where)->select()->toArray();

        if($bookInfo){ // 请勿重复预约

            $msg = '您已预约当前时间，请勿重复预约！';

        }else{

            $data = [

                'customer_id' => $customer_id,

                'shop_person_id' => $shop_person_id,

                'shop_id' => $shop_id,

                'yy_time' => $yyTime,

                'create_time' => time(),

                'status' => 0, // 0代表正常，1代表取消，

            ];

            $bookId = Db::name('books')->insertGetId($data); // 新增xy_books表数据


            if($bookId){

                $msg = '预约成功！';

            }else{

                $msg = '预约失败，请重新提交！';

            }

        }

        return $res = [

            'msg' => $msg,

        ];

        // exit;
    }

    // 修改护理师预约看板
    public function updateStaffData($shop_person_id,$year,$date,$time,$shop_id,$type)
    {
        // echo $shop_person_id;
        // echo "<br/>";
        // echo $year;
        // echo "<br/>";
        // echo $date;
        // echo "<br/>";
        // echo $time;
        // echo "<br/>";
        // echo $shop_id;
        // echo "<br/>";

        $dateArr = explode('-',$date);

        // echo "<pre>";
        // print_r($dateArr);
        // echo "</pre>";

        $timeStr = $year.$dateArr[0].$dateArr[1];

        $where = [];

        array_push($where,['shop_person_id','=',$shop_person_id]);

        array_push($where,['time','=',$timeStr]);

        $book_str = Db::name('shop_person_schedule')->where($where)->value('yy_time');

        // echo "<pre>";
        // print_r($where);
        // echo "</pre>";
        // exit;

        $book_arr = str_split($book_str);



        // 门店营业开始时间
        $shop_start_time = Db::name('shop')->where('shop_id',$shop_id)->value('start_time');

        // echo $shop_start_time;

        $chooseDate = $year.'-'.$date;

        $time1 = strtotime($chooseDate.' '.$shop_start_time);
        $time2 = strtotime($chooseDate.' '.$time);

        $timeDifference = bcsub($time2,$time1);

        $key_num = $timeDifference/1800;

        $thisTimeBookNum = $book_arr[$key_num];



        if($type == 'add'){ // 新增预约

            if($thisTimeBookNum == 0){ // 可以预约

                $book_arr[$key_num] = bcadd($thisTimeBookNum,1,0);

            }else{

                return $time;

            }


        }

        if($type == 'sub'){ // 取消预约

            $book_arr[$key_num] = bcsub($thisTimeBookNum,1,0);

        }

        $new_book_str = implode($book_arr);

        $updateArr = [

            'yy_time' => $new_book_str,

        ];

        // echo "<pre>";
        // print_r($updateArr);
        // echo "</pre>";
        // exit;

        $bool = Db::name('shop_person_schedule')->where($where)->update($updateArr);

        if($bool){
            return true;
        }else{
            return false;
        }




    }

    public function getBookList($request): array
    {
        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";

        $where = [];

        array_push($where,['customer_id','=',$request['customer_id']]);

        array_push($where,['is_use','=',0]);

        array_push($where,['status','=',0]); // 未取消的预约

        $bookList = Db::name('books')->where($where)->order('yy_time desc')->select()->toArray();

        $shop_ids = array_values(array_unique(array_column($bookList,'shop_id'))); // 获取预约信息中的门店id

        $where = [];

        array_push($where,['shop_id','in',$shop_ids]);

        $shop_names = Db::name('shop')->where($where)->column('shop_name','shop_id');



        $shop_person_ids =  array_values(array_unique(array_column($bookList,'shop_person_id'))); // 获取预约信息中的护理师id

        $where = [];

        array_push($where,['id','in',$shop_person_ids]);

        $shop_person_names = Db::name('shop_person')->where($where)->column('name','id');

        $list = [];

        foreach ($bookList as $key => $value) {

            // 预约时间戳的前15分钟
            $beforeMinute15 = $value['yy_time']-(30*60);

            if(time()<$beforeMinute15){
                $isCancel = 0; // 可以取消
            }else{
                $isCancel = 1; // 不可取消
            }


            // 今日日期
            $today = date('Ymd',time());

            // $today2 = date('Y-m-d',time());

            // 预约日期
            $yyDate = date('Ymd',$value['yy_time']) ?? '';

            if($yyDate<$today){

                $yy_status = 0; // 已过期

            }else{

                $yy_status = 1; // 待核销

            }

            // 预约时长
            $length = '';

            if($value['yy_time_str']){

                $yy_time_arr = explode(',',$value['yy_time_str']);

                $length = count($yy_time_arr)*0.5;

                $end_time = date('H:i',($value['yy_time']+(1800*count($yy_time_arr))));

            }else{

                $end_time = date('H:i',($value['yy_time']+1800));

                $length = 0.5;

            }



            $one = [];

            $one['id'] = $value['id'];

            $one['shop_person_name'] = $shop_person_names[$value['shop_person_id']] ?? '';

            $one['shop_name'] = $shop_names[$value['shop_id']] ?? '';

            $one['yy_date'] = date('Y-m-d',$value['yy_time']) ?? '';

            $one['yy_time'] = date('H:i',$value['yy_time']).'-'.$end_time ?? '';

            $one['yy_time_str'] = $value['yy_time_str'] ?? '';

            $one['yy_length'] = $length;

            $one['create_time'] = date('Y-m-d H:i',$value['create_time']) ?? '';

            $one['status'] = $value['status'] ?? '';

            $one['yy_status'] = $yy_status;

            $one['today'] = $today;

            $one['isCancel'] = $isCancel;

            array_push($list,$one);

        }

        // echo "<pre>";
        // print_r($list);
        // echo "</pre>";

        // exit;
        return $list;
    }

    // 客户提交满意度调查接口
    public function addQuestionCustomer($request): array
    {


        $customer_id = $request['customer_id'];

        $shop_id = Db::name('customer')->where('id',$customer_id)->value('shop_id');

        $questionId = $request['questionId'];

        $where = [];

        array_push($where,['customer_id','=',$customer_id]);

        array_push($where,['questionnaire_id','=',$questionId]);

        $question_customer_info = Db::name('question_customer')->where($where)->select()->toArray();

        // echo "<pre>";
        // print_r($question_customer_info);
        // echo "</pre>";
        // exit;

        if(empty($question_customer_info)){

            $answers = implode(',',$request['answers']);

            $data = [

                'customer_id' => $customer_id,

                'questionnaire_id' => $questionId,

                'shop_id' => $shop_id,

                'answers' => $answers,

                'create_time' => time(),

            ];

            $question_customer_id = Db::name('question_customer')->insertGetId($data); // 插入数据库

            if($question_customer_id){

                if($questionId == 6){
                    // 发放产品兑换卷

                    $customerPointGoodsBuy = new CustomerPointGoodsBuy();

                    $customerPointGoodsBuy->save([
                        'point_goods_id'=>'26',
                        'customer_id'=>$customer_id,
                        'status'=>1
                    ]);
                    
                }else{
                    // 获取积分
                    CustomerPointModel::pointChange($customer_id,9);

                }

                return [

                    'msg' => '感谢您对我们的支持！',

                ];

            }else{

                return [

                    'msg' => '数据异常！',

                ];

            }

        }else{

            return [

                'msg' => '请勿重复提交！',

            ];

        }

    }


    // 取消预约模型
    public function cancelBook($request,$app): array
    {
        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";
        // exit;

        $bookInfo = Db::name('books')->where('id',$request['bookId'])->select()->toArray();

        $shop_id = $bookInfo[0]['shop_id'];

        $shopInfo = Db::name('shop')->where('shop_id',$shop_id)->select()->toArray();

        $startWorkTimeStr = $shopInfo[0]['start_time'];

        // 修改books表数据

        $updateBooks = [
            'status' => 1,
        ];

        $bool = Db::name('books')->where('id',$request['bookId'])->update($updateBooks);

        // 修改员工排班表数据
        $shop_person_id = $bookInfo[0]['shop_person_id'];

        $time = $request['yy_time'];

        if($bookInfo[0]['yy_time_str']){

            $yy_time_arr = explode(',',$bookInfo[0]['yy_time_str']);

        }else{

            $yy_time_arr = [];

            array_push($yy_time_arr,$time);
        }


        $dateArr = explode('-',$request['yy_date']);

        $year = $dateArr[0];

        $date = $dateArr[1].'-'.$dateArr[2];

        foreach ($yy_time_arr as $key => $value) {

            $bookRes = $this->updateStaffData($shop_person_id,$year,$date,$value,$shop_id,'sub');

        }


        if($bookRes){

            CustomerPointModel::pointChange($bookInfo[0]['customer_id'],10);
            $customer = Customer::find($bookInfo[0]['customer_id']);
            $person = PersonModel::find($shop_person_id);
            $qyWechat = new QyWechatController($app);
            $qyWechat->index('cancelReservationAction',[
                'mobile'=>$person->phone,
                'start'=>$year.'-'.$date.' ',
                'end'=>$time,
                'customer_name'=>$customer->customer_name
            ]);

            return [
                'data' =>'取消成功',
            ];
        }else{
            return [
                'data' =>'取消失败',
            ];
        }

    }

    // 获取setting 14
    public function getSetting14($request): array
    {
        $category_id = $request['category_id'];

        $where = [];

        array_push($where,['category_id','=',$category_id]);

        $res = Db::name('setting')->where($where)->column('id,name');

        return $res;
    }
    /**
     * 一次性设置一周排班
     */
    public function setScheduleWeek($request)
    {
        // $start = date('Ymd',strtotime('+1 week last monday'));
        // $end = date('Ymd',strtotime('+1 week next sunday'));
        // print_r(strtotime('+1 week last monday'));
        // exit;
        $staffId = $request['id'];
        $shopId = $request['shop_id'];
        $yyTime = "00000000000000000000000";
        $create_time = time();
        $insertData = [];
        $startTime = strtotime(date('Y-m-d',time()));
        $end_time = strtotime(date('Y-m-7',strtotime('next month')));
        $msg = "编辑成功";
        for ($i=$startTime; $i <= $end_time; $i+=24*60*60) {
            $insertData = [
                'time' => date('Ymd',$i),
                'shop_id' => $shopId,
                'shop_person_id' => $staffId,
                'is_work' => 1,
                'work_type' => 0,
                'yy_time'=>$yyTime,
                'create_time'=>$create_time
            ];
            $where = [];

            array_push($where,['shop_person_id','=',$staffId]);

            array_push($where,['time','=',date('Ymd',$i)]);

            $schedule = Db::name('shop_person_schedule')->where($where)->select()->toArray();
            if($schedule)
            {
                if(strpos($schedule[0]['yy_time'],'1') !== false){
                    // return ['msg' => '编辑失败', 'data' => [],'code'=>300];
                    $msg  = "已被预约日期未编辑";
                }else{
                    $res = Db::name('shop_person_schedule')->where($where)->update($insertData);
                }
            }else{
                $res = Db::name('shop_person_schedule')->save($insertData);
            }
        }
        return ['msg' => $msg, 'data' => [],'code'=>200];
    }


    // 获取市场的门店id列表
    public function getShopIds($request)
    {

        $marketId = $request['marketId'];

        $where = [];
        array_push($where,['market_id','in',$marketId]);
        array_push($where,['type','<>','2']);
        array_push($where,['status','=','1']);

        $shop_ids = Db::name('shop')->where($where)->column('shop_id');

        // echo "<pre>";
        // print_r($shop_ids);
        // echo "</pre>";
        return $shop_ids;
    }

    // 获取轮播图展示列表
    public function getBannerList($request){
        $where = [];

        if($request['type'] == 'mini'){
            array_push($where,['use_status','=','1']);
        }

        $list = Db::name('mini_banner')->where($where)->select()->toArray();

        $data = [];

        $data['list'] = $list ?? [];

        $data['dataCount'] = $dataCount ?? 0;

        return $data;
    }
}
